<script setup>
import { ref } from 'vue'
import { usePostStore } from '@/stores/index.js'
import { useUserStore } from '@/stores/index.js'
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
import { publishPostService } from '@/apis/publish.js'
const UserStore = useUserStore()
const PostStore = usePostStore()

// 获取表单实例
const form = ref(null)

// 图片列表
const imagesList = ref([])

// 表单绑定的数据
const formModel = ref({
	title: '',
	content: '',
	images: [],
	type: '',
	association_id: '',
	is_agree: false,
	locationName: ''
})

// 表单验证规则
const rules = ref({
	title: [{ type: 'string', required: true, message: '请填写标题' }],
	content: [{ type: 'string', required: true, message: '请填写内容' }],
	locationName: [{ type: 'string', required: true, message: '请添加地点' }],
	images: [{ type: 'array', required: true, message: '请上传图片' }],
	is_agree: [{ type: 'boolean', required: true, message: '请同意社区规则' }]
})

// 删除图片
const deletePic = (e) => {
	imagesList.value.splice(e.index, 1)
}

// 新增图片
const afterRead = async (event) => {
	// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
	let lists = [].concat(event.file)
	let fileListLen = imagesList.value.length
	lists.map((item) => {
		imagesList.value.push({
			...item,
			status: 'uploading',
			message: '上传中'
		})
	})
	for (let i = 0; i < lists.length; i++) {
		const result = await uploadFilePromise(lists[i].url)
		let item = imagesList.value[fileListLen]
		imagesList.value.splice(fileListLen, 1, {
			...item,
			status: 'success',
			message: '',
			url: result.url
		})
		fileListLen++
	}

	formModel.value.images = imagesList.value
}

// 上传图片
const uploadFilePromise = (url) => {
	return new Promise((resolve, reject) => {
		let a = uni.uploadFile({
			url: 'https://www.u2051641.nyat.app:64347/post/upload',
			filePath: url,
			name: 'file',
			header: {
				Authorization: `Bearer ${UserStore.UserInfoList.token}`
			},
			success: (res) => {
				setTimeout(() => {
					resolve(JSON.parse(res.data))
				}, 100)
			}
		})
	})
}

// 点击添加地点选项跳转到搜索页面选择地点
const goToSearch = () => {
	uni.navigateTo({
		url: '/ExplorePackage/Search/Search?searchAll=false'
	})
}

// 点击按钮发布帖子
const onClickButton = () => {
	// 验证表单数据
	form.value
		.validate()
		.then(async (valid) => {
			if (valid) {
				// 获取用户ID
				const user_id = UserStore.UserInfoList.user_id

				// 将用户ID添加到表单
				formModel.value.user_id = user_id

				// 对表单数据进行处理,准备提交数据
				const formatImages = formModel.value.images.map((item) => {
					return {
						url: item.url
					}
				})

				formModel.value.images = formatImages
				const res = await publishPostService(formModel.value)
				// 清空表单域
				form.value.resetFields()
				imagesList.value = []

				// 清空本地存储和pinia
				PostStore.clearPostData()

				// 发布成功提示并跳转社区页面
				uni.showToast({
					title: '发布成功',
					icon: 'success'
				})

				setTimeout(() => {
					uni.switchTab({
						url: '/pages/community/community'
					})
				}, 2000)
			}
		})
		.catch((err) => {
			if (err && err[0]) {
				uni.showToast({
					title: err[0].message,
					icon: 'error'
				})
			}
		})
}

// 确认放弃编辑时触发函数
const onClickConfirm = () => {
	// 清空本地存储和pinia
	PostStore.clearPostData()
}

onLoad((option) => {
	// 退出当前页面时进行询问确认
	wx.enableAlertBeforeUnload({
		message: '你确定要放弃编辑吗'
	})
})

onUnload(() => {
	// 清空本地存储和pinia
	PostStore.clearPostData()
})

onShow(() => {
	formModel.value = PostStore.postData
	if (PostStore.postData.images) {
		imagesList.value = PostStore.postData.images
	}
})
</script>

<template>
	<view class="container">
		<view class="content">
			<up-form labelPosition="left" :model="formModel" :rules="rules" ref="form" errorType="none">
				<up-form-item prop="images">
					<up-upload :fileList="imagesList" @afterRead="afterRead" @delete="deletePic" name="3" multiple :maxCount="10" :previewFullImage="true"></up-upload>
				</up-form-item>

				<up-form-item prop="title" borderBottom>
					<up-input placeholder="请输入标题" v-model.trim="formModel.title" border="none"></up-input>
				</up-form-item>

				<up-form-item prop="content">
					<up-textarea placeholder="请输入内容" v-model.trim="formModel.content" maxlength="-1" border="bottom" height="200"></up-textarea>
				</up-form-item>

				<up-form-item @tap="goToSearch" prop="locationName">
					<up-input border="none" v-model="formModel.locationName" inputAlign="center" readonly>
						<template #prefix>
							<view class="left">
								<up-icon name="map-fill" size="20"></up-icon>
								<view class="text">添加地点</view>
							</view>
						</template>
						<template #suffix>
							<up-icon name="arrow-right" size="20"></up-icon>
						</template>
					</up-input>
				</up-form-item>

				<up-form-item prop="is_agree">
					<up-checkbox :customStyle="{ marginBottom: '8px' }" label="同意《乐游汇社区发布规则》" shape="circle" usedAlone v-model:checked="formModel.is_agree"></up-checkbox>
				</up-form-item>
			</up-form>
		</view>

		<view class="footer">
			<view class="footer-btn" @tap="onClickButton">发布</view>
		</view>
	</view>
</template>

<style lang="scss" scoped>
.container {
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	height: 100vh;
	background-color: #fff;

	.content {
		padding: 30rpx;
		flex: 1;

		::v-deep .u-form {
			height: 100%;
		}

		.left {
			display: flex;
			font: size 30rpx;
			font-weight: bold;

			.text {
				margin-left: 20rpx;
			}
		}
	}

	.footer {
		padding: 60rpx 20rpx;
		border-top: 4rpx solid #f8f8f8;

		.footer-btn {
			padding: 20rpx;
			border-radius: 999px;
			display: flex;
			justify-content: center;
			align-items: center;
			color: #fff;
			font-size: 35rpx;
			background-image: linear-gradient(to top, #00c6fb 0%, #005bea 100%);
		}
	}
}
</style>
